const express = require('express');
const router = express.Router();
const sql = require("../sql/index");
const User = require("../sql/collection/User");
const uuid = require("node-uuid");
const send = require("../utils/index");
const md5 = require("md5");
const jwt = require("jsonwebtoken");
const utils = require('../utils/index');
/**
* @api {post} /api/user/docheckphone 注册：检测手机号
* @apiName PostApiDocheckphone
* @apiGroup User
* 
* @apiParam { String } tel 手机号
* 
* @apiSuccessExample { json } Success-Response:
    res.send({
        code: "200",
        message: "手机号未注册，继续注册"
    });
    res.send({
        code: "10002",
        message: "手机号已注册，请登录",
        tel
    })
* @apiSampleRequest /api/user/docheckphone
* @apiVersion 0.0.0
*/
// 检测手机号
router.post('/docheckphone', function (req, res, next) {
    // 获取手机号
    let { tel } = req.body;
    // 检测手机号是否存在
    sql.find(User, { tel }, { _id: 0 }).then((data) => {
        if (data.length === 0) {
            // 手机号不存在 直接插入数据
            // 生成随机6位验证码
            const telCode = Math.floor(Math.random() * 900000 + 100000);
            // 插入的数据
            let insertData = {
                userid: "user_" + uuid.v1(),
                username: "",
                password: "",
                nickname: "",
                email: "",
                tel,
                hobby: [],
                birthday: 0,
                sex: -1,
                avatar: 0,
                telCode,
                loginStart: 0,
                regTime: 0,
                nowTime: 0,
                lastTime: 0
            };
            sql.insert(User, insertData).then(() => {
                res.send({
                    code: "200",
                    message: "手机号未注册，继续注册",
                    tel
                });
            })
        } else {
            if (data[0].password === "") {
                res.send({
                    code: "200",
                    message: "手机号未注册，继续注册",
                    tel
                });
            } else {
                res.send({
                    code: "10002",
                    message: "手机号已注册，请登录"
                });
            }
        }
    })
});
/**
* @api {post} /api/user/dosendmsgcode 注册：发送验证码
* @apiName PostApiDosendmsgcode
* @apiGroup User
* 
* @apiParam { String } tel 手机号
* 
* @apiSuccessExample { json } Success-Response:
        res.send({
            code: "200",
            message: "验证码发送成功",
            telCode
        });
        res.send({
            code: "10003",
            message: "手机号已注册"
        });
        res.send({
            code: "10004",
            message: "验证码发送失败：" + result
        });
* @apiSampleRequest /api/user/dosendmsgcode
* @apiVersion 0.0.0
*/
// 发送验证码 dosendmsgcode 
router.post("/dosendmsgcode", (req, res, next) => {
    // 获取手机号
    let { tel } = req.body;
    // 生成随机6位验证码
    const telCode = Math.floor(Math.random() * 900000 + 100000);
    // 发送验证码
    send.sendCode(tel, telCode).then(() => {
        // 查询手机号是否注册
        sql.find(User, { tel }, { _id: 0 }).then(data => {
            if (data.length === 0) {
                // 手机号不存在 直接插入数据
                let insertData = {
                    userid: "user_" + uuid.v1(),
                    username: "",
                    password: "",
                    nickname: "",
                    email: "",
                    tel,
                    hobby: [],
                    birthday: 0,
                    sex: -1,
                    avatar: 0,
                    telCode,
                    loginStart: 0,
                    regTime: 0,
                    nowTime: 0,
                    lastTime: 0
                }
                sql.insert(User, insertData).then(() => {
                    res.send({
                        code: "200",
                        message: "验证码发送成功"
                    });
                })
            } else {
                if (data[0].password === "") {
                    sql.update(User, { tel }, { $set: { telCode } }).then(() => {
                        res.send({
                            code: "200",
                            message: "验证码发送成功"
                        });
                    });
                } else {
                    res.send({
                        code: "10003",
                        message: "手机号已注册"
                    });
                }
            }
        });
    }, (result) => {
        // 验证码发送失败
        res.send({
            code: "10004",
            message: "验证码发送失败：" + result
        });
    })
})
/**
* @api {post} /api/user/docheckcode 注册：检测验证码
* @apiName PostApiDocheckcode
* @apiGroup User
* 
* @apiParam { String } tel 手机号
* @apiParam { Number } telCode 验证码
* 
* @apiSuccessExample { json } Success-Response:
        res.send({
            code: "200",
            message: "验证码验证成功",
            tel
        });
        res.send({
            code: "10004",
            message: "手机号未注册"
        });
        res.send({
            code: "10005",
            message: "验证码验证失败"
        });
* @apiSampleRequest /api/user/docheckcode
* @apiVersion 0.0.0
*/
// 检测验证码   docheckcode 
router.post("/docheckcode", (req, res, next) => {
    let { tel, telCode } = req.body;
    // 转换数据类型
    telCode *= 1;
    // 先检测手机号是否存在
    sql.find(User, { tel }, { _id: 0 }).then(data => {
        if (data.length === 0) {
            // 手机号不存在 直接插入数据
            // 生成随机6位验证码
            const telCode = Math.floor(Math.random() * 900000 + 100000);
            // 插入的数据
            let insertData = {
                userid: "user_" + uuid.v1(),
                username: "",
                password: "",
                nickname: "",
                email: "",
                tel,
                hobby: [],
                birthday: 0,
                sex: -1,
                avatar: 0,
                telCode,
                loginStart: 0,
                regTime: 0,
                nowTime: 0,
                lastTime: 0
            };
            sql.insert(User, insertData).then(() => {
                res.send({
                    code: "10004",
                    message: "手机号未注册"
                });
            })
        } else {
            // 手机号存在，验证验证码
            if (telCode === data[0].telCode) {
                // 验证码验证成功  修改验正码
                const telCode = Math.floor(Math.random() * 900000 + 100000);
                sql.update(User, { tel }, { $set: { telCode } }).then(() => {
                    res.send({
                        code: "200",
                        message: "验证码验证成功",
                        tel
                    });
                })
            } else {
                // 验证码验证失败
                res.send({
                    code: "10005",
                    message: "验证码验证失败"
                });
            }
        }
    })
})
/**
* @api {post} /api/user/dosetpassword 注册：设置用户密码
* @apiName PostApiDosetpassword
* @apiGroup User
* 
* @apiParam { String } tel 手机号
* @apiParam { String } password 密码
* 
* @apiSuccessExample { json } Success-Response:
        res.send({
            code: "200",
            message: "注册成功",
            tel
        });
* @apiSampleRequest /api/user/dosetpassword
* @apiVersion 0.0.0
*/
// 设置密码
router.post("/dosetpassword", (req, res, next) => {
    let { tel, password } = req.body;
    password = md5(password);
    let upDate = {
        password,
        loginStart: 0,
        regTime: Date.now()
    };
    sql.update(User, { tel }, { $set: upDate }).then(() => {
        res.send({
            code: "200",
            message: "注册成功"
        });
    })
})
// 验证码登录
/**
* @api {post} /api/user/dosendlogincode 登录：发送验证码
* @apiName PostApiDosendlogincode
* @apiGroup User
* 
* @apiParam { String } tel 手机号
* 
* @apiSuccessExample { json } Success-Response:
        res.send({
            code: "200",
            message: "验证码发送成功"
        })
        res.send({
            code: "10006",
            message: "未注册"
        });
        res.send({
            code: "10007",
            message: "验证码发送失败" + err
        })
* @apiSampleRequest /api/user/dosendlogincode
* @apiVersion 0.0.0
*/
// 验证码登录  dosendlogincode 发送验证码
router.post("/dosendlogincode", (req, res, next) => {
    let { tel } = req.body;
    sql.find(User, { tel }, { _id: 0 }).then(data => {
        if (data.length === 0 || data[0].password === "") {
            res.send({
                code: "10006",
                message: "未注册"
            })
        } else {
            const telCode = Math.floor(Math.random() * 900000 + 100000);
            utils.sendCode(tel, telCode).then(() => {
                sql.update(User, { tel }, { $set: { telCode } }).then(() => {
                    res.send({
                        code: "200",
                        message: "验证码发送成功"
                    })
                })
            }, (err) => {
                res.send({
                    code: "10007",
                    message: "验证码发送失败" + err
                })
            })
        }
    })
})
/**
* @api {post} /api/user/dosmslogin 登录：检测验证码
* @apiName PostApiDosmslogin
* @apiGroup User
* 
* @apiParam { String } tel 手机号
* @apiParam { Number } telCode 验证码
* 
* @apiSuccessExample { json } Success-Response:
        res.send({
            code: "200",
            message: "登录成功",
            data: {
                userid: data[0].userid,
                token
            }
        })
        res.send({
            code: "10006",
            message: "未注册"
        });
        res.send({
            code: "10008",
            message: "验证码验证失败"
        })
* @apiSampleRequest /api/user/dosmslogin
* @apiVersion 0.0.0
*/
// 登录：检测验证码 dosmslogin
router.post("/dosmslogin", (req, res, next) => {
    let { tel, telCode } = req.body;
    telCode *= 1;
    sql.find(User, { tel }, { _id: 0 }).then((data) => {
        if (data.length === 0 || data[0].password === "") {
            res.send({
                code: "10006",
                message: "未注册"
            })
        } else {
            if (data[0].telCode === telCode) {
                // 改变验证码
                const telCode = Math.floor(Math.random() * 900000 + 100000);
                let upDate = {
                    telCode,
                    loginStart: 1,
                    nowTime: Date.now()
                }
                sql.update(User, { tel }, { $set: upDate }).then(() => {
                    // 生成token
                    const token = jwt.sign({ userid: data[0].userid }, 'cmhtokenkey', {
                        expiresIn: 7 * 24 * 60 * 60
                    })
                    res.send({
                        code: "200",
                        message: "登陆成功",
                        data: {
                            userid: data[0].userid,
                            token
                        }
                    })
                })
            } else {
                res.send({
                    code: "10008",
                    message: "验证码验证失败"
                })
            }
        }
    })
})
/**
* @api {post} /api/user/domlogin 登录：账号密码验证
* @apiName PostApiDomlogin
* @apiGroup User
* 
* @apiParam { String } loginname 用户名、邮箱、手机号
* @apiParam { String } password 密码
* 
* @apiSuccessExample { json } Success-Response:
        res.send({
            code: "10006",
            message: "未注册"
        });
        res.send({
            code: "200",
            message: "登录成功",
            data: {
                userid: data[0].userid,
                token
            }
        });
        res.send({
            code: "10009",
            message: "登录失败"
        });
* @apiSampleRequest /api/user/domlogin
* @apiVersion 0.0.0
*/
// 其他登录 domlogin 用户名、邮箱、手机号 + 密码  登录
router.post("/domlogin", (req, res, next) => {
    let { loginname, password } = req.body;
    // 密码使用md5加密
    password = md5(password);
    sql.find(User, { $or: [{ username: loginname }, { email: loginname }, { tel: loginname }] }, { _id: 0 }).then((data) => {
        if (data.length === 0 || data[0].password === "") {
            res.send({
                code: "10006",
                message: "未注册"
            });
        } else {
            // 验证密码是否正确
            if (password === data[0].password) {
                // 设置登录状态和当前登陆时间
                let upDate = {
                    loginStart: 1,
                    nowTime: Date.now()
                }
                sql.update(User, { tel: data[0].tel }, { $set: upDate }).then(() => {
                    // 生成token
                    const token = jwt.sign({ userid: data[0].userid }, 'cmhtokenkey', {
                        expiresIn: 7 * 24 * 60 * 60
                    })
                    res.send({
                        code: "200",
                        message: "登录成功",
                        data: {
                            userid: data[0].userid,
                            token
                        }
                    });
                })
            } else {
                res.send({
                    code: "10009",
                    message: "登录失败"
                });
            }
        }
    })
})
/**
* @api {post} /api/user/userinfo 获取个人信息
* @apiName PostApiUserInfo
* @apiGroup User
* 
* @apiParam { String } userid 用户ID
* @apiParam { String } token token
* 
* @apiSuccessExample { json } Success-Response:
        res.send({
            code: '200',
            message: '个人信息',
            data: data[0]
        })
* @apiSampleRequest /api/user/userinfo
* @apiVersion 0.0.0
*/
// 获取个人信息
router.post('/userinfo', (req, res, next) => {
    let { userid } = req.body;
    utils.verifyToken(req, res).then(() => {
        sql.find(User, { userid }, { _id: 0}).then(data => {
            res.send({
                code: '200',
                message: '个人信息',
                data: data[0]
            })
        })
    })
})
module.exports = router;
